const index = {
    template: getHtml("./views/index.html")
}
const info = {
    template: "<h1>INFO</h1>"
}
const other = {
    template: "<p>other</p>"
}

const userList = {
    template: getHtml("./views/userSelect.vue")
}
const userInfo = {
    template: getHtml("./views/userInfo.vue")
}
const imgList = {
    template: getHtml("./views/imgList.vue")
}
const uploadImg = {
    template: getHtml("./views/uploadImg.vue")
}

const routes = [{
    path: "/index",
    component: index,
    children: [{
        path: "/index/userList",
        component: userList
    }, {
        path: "/index/imgList",
        component: imgList
    }, {
        path: "/index/userInfo",
        component: userInfo
    }, {
        path: "/index/uploadImg",
        component: uploadImg
    }, {
        path: '/index/',
        redirect: '/index/userList'
    }]
}, {
    path: "/info",
    component: info
}, {
    path: "/other",
    component: other,
}, {
    path: '/',
    redirect: '/index'
}]


const router = new VueRouter({
    routes // （缩写）相当于 routes: routes
})
new Vue({
    el: "#myBox",
    router,
    data: function () {
        return {
            test: "OK",
            show: 0,
            username: sessionStorage.getItem("username"),
        }
        // return {
        //     test:"OK",
        //     show: 0,
        //     username: sessionStorage.getItem("username"),
        //     pageList: {
        //         page: 1,
        //         allCount: 0,
        //         curPage: 1,
        //         allPage: 1,
        //         count: 10,
        //         searchVal: "",
        //         toPageNum: 0,
        //         pageData: {}
        //     },
        //     ul_editData: {
        //         editId: "",
        //         ul_editName: "",
        //         ul_editPasswd: "",
        //         ul_editTel: "",
        //         ul_editAddr: "",
        //         ul_editBirthday: "",
        //         ul_editSex: "男",
        //     },
        //     ul_addData: {
        //         ul_addId: "",
        //         ul_addName: "",
        //         ul_addPasswd: "",
        //         ul_addTel: "",
        //         ul_addAddr: "",
        //         ul_addBirthday: "",
        //         ul_addSex: "男",
        //     }
        // }
    },
    created: function () {
        // getSearchUser(this.searchVal, this.page, this.count);
    },
    watch: {
        $route(to, from) {
            // to表示的是你要去的那个组件，from 表示的是你从哪个组件过来的，它们是两个对象，你可以把它打印出来，它们也有一个param 属性
            console.log("fromName", from.fullPath, " ---> ", to.fullPath);
            if (to.fullPath == "/index/userInfo") {

            } else if ("/index/userList") {
                // getSearchUser(this.searchVal, this.page, this.count);
            } else if ("/index/imgList") {

            } else if ("/index/uploadImg") {
                inputFileFun();
            }
        }
    },
    mounted: function () {
        this.sessionStorage = sessionStorage.getItem("username");
        if (sessionStorage.getItem("flag") == 'true') { //0--登录  1--注销
            this.show = 1;
        } else {
            this.show = 0;
        }

        // getSearchUser(this.pageList.searchVal, this.pageList.page, this.pageList.count);

    },
    methods: {
        login: function () {
            // console.log("login");
            location.href = "./views/login.html";
        },
        logout: function () {
            // console.log("logout");
            sessionStorage.clear();
            location.href = "./views/login.html";
        },
        getUserList: function () {
            getSearchUser("", 1, 10);
        },
        getUserInfo:function(){
            getData();
        },
        getImgList:function(){

        },
        addImg:function(){
            inputFileFun();
        }
    }
});

function autoHeight() {
    var height = document.body.clientHeight;
    // var height = window.innerHeight;
    $(".content").css("height", (height - 120) + "px");
}

function getHtml(url) {
    var rest = null;
    $.ajax({
        url: url,
        method: 'get',
        async: false,
        success: function (res) {
            rest = res;
        }
    })
    return rest;
}

function inputFileFun() {
    $("#myfile").fileinput({
        uploadUrl: "http://127.0.0.1:8888/linkMan/linkman/uploadFile", //上传的地址
        uploadAsync: true, //默认异步上传
        showUpload: true, //是否显示上传按钮,跟随文本框的那个
        showRemove: true, //显示移除按钮,跟随文本框的那个
        showCaption: true, //是否显示标题,就是那个文本框
        showPreview: true, //是否显示预览,不写默认为true
        dropZoneEnabled: true, //是否显示拖拽区域，默认不写为true，但是会占用很大区域
        maxFileCount: 9, //表示允许同时上传的最大文件个数
        enctype: 'multipart/form-data',
        validateInitialCount: true,
        previewFileIcon: "<i class='glyphicon glyphicon-king'></i>",
        msgFilesTooMany: "选择上传的文件数量({n}) 超过允许的最大数值{m}！",
        allowedFileTypes: ['image'], //配置允许文件上传的类型
        allowedPreviewTypes: ['image'], //配置所有的被预览文件类型
        allowedPreviewMimeTypes: ['jpg', 'png', 'gif', 'bmp', 'svg'], //控制被预览的所有mime类型
        language: 'zh',
        uploadExtraData: function (previewId, index) { //额外参数的关键点
            var sendData = {};
            sendData.id = "11001";
            // sendData.name = $("#username").val();
            sendData.name = "huacx";
            console.log("sendData:", sendData);
            // obj.fodder = fodderType();
            // console.log(obj);
            return sendData;
        }
    }).on('fileuploaded', function (event, data, previewId, index, fileId) {
        console.log("fileuploaded data: ", data.response)
    }).on('fileuploaderror', function (event, data, msg) {

    }).on('filebatchuploadcomplete', function (event, preview, config, tags,
        extraData) {

    }).on("filebatchselected", function (event, files) {
        console.log(" filebatchselected change")
    }).on("fileimageuploaded", function (params) {
        console.log(" fileimageuploaded end");
    }).on('filebatchuploaderror', function (event, data, msg) { //同步上传错误处理
        console.log("filebatchuploaderror");
    }).on("filebatchuploadsuccess", function (event, data, previewId, index) {
        console.log("filebatchuploadsuccess");
    }).on('filepreupload', function (event, data, previewId, index) {
        console.log("filepreupload");
    });
    $("#upfile").fileinput("upload");
}

// 初始化及限制生日
function initDate() {
    var date_now = new Date();
    var year = date_now.getFullYear();
    var month = date_now.getMonth() + 1 < 10 ? "0" + (date_now.getMonth() + 1) : (date_now.getMonth() + 1);
    var date = date_now.getDate() < 10 ? "0" + date_now.getDate() : date_now.getDate();
    var disDate = year + "-" + month + "-" + date;
    //设置input标签的max属性
    // $("input[name='addBirthday']").attr("max", disDate);
    // $("input[name='t_addBirthday']").attr("max", disDate);
    // $("input[name='addBirthday']").val(disDate);
    // $("input[name='t_addBirthday']").val(disDate);
    $("input[type='date']").val(disDate);
}

// 删除用户
function delUser(userid) {
    $.ajax({
        url: "http://127.0.0.1:8888/linkMan/linkman/delUser",
        method: "post",
        dataType: 'json',
        async: false,
        data: {
            "id": userid
        },
        success: function (res) {
            // alert(res.msg);
            console.log("post res: ", res);
        },
        error: function (error) {
            console.log("post error: ", error)
        }
    });
}

// 操作用户
function operationUser(data, url) {
    $.ajax({
        url: url,
        method: "post",
        dataType: 'json',
        async: false,
        data: data,
        success: function (res) {
            console.log("post res: ", res);
            alert(res.msg);
        },
        error: function (error) {
            console.log("post error: ", error);
        }
    });
}

// 分页查找
function getSearchUser(searchVal, page, count) {
    console.log("--", searchVal, page, count);
    var that = this;
    $.ajax({
        url: "http://127.0.0.1:8888/linkMan/linkman/selectByPage",
        method: 'post',
        dataType: 'json',
        data: {
            searchVal: searchVal,
            pageNum: page,
            count: count
        },
        success: function (res) {
            console.log("allCount: ", res);
            var _html = "";
            this.pageData = res.data;
            that.allCount = res.count;
            that.allPage = Math.ceil(allCount / count);
            // $(".allCount").text(allCount);
            // $(".allPage").text(allPage);
            // $("#tb").html("");
            // insertHtml(data, queryUser);
            // for (var i = 0; i < data.length; i++) {
            //     var inHtml = "<tr>";
            //     inHtml += "<td>" + data[i].id + "</td>";
            //     inHtml += "<td>" + data[i].username + "</td>";
            //     inHtml += "<td>" + data[i].passwd + "</td>";
            //     inHtml += "<td>" + data[i].addr + "</td>";
            //     inHtml += "<td>" + data[i].tel + "</td>";
            //     inHtml += "<td>" + data[i].gender + "</td>";
            //     // inHtml += "<td>" + data[i].work + "</td>";
            //     inHtml += "<td>" + data[i].birthday + "</td>";
            //     inHtml += "<td><b class='edit btn'  data-target='#editModal'>修改</b></td>";
            //     inHtml += "<td><b class='add btn'  data-target='#addModal'>添加</b></td>";
            //     inHtml += "<td><b class='del btn' data-target='#delModal'>删除</b></td>";
            //     // inHtml += "<td class='plus'><b>+</b></td></tr>";
            //     _html += inHtml;
            // }
            // $("#tb").html(_html);
        },
        error: function (error) {}
    });
}

// 点击事件
function events() {
    $(".searchBtn").click(function () {
        searchVal = $(".search").val() || ""
        getSearchUser(searchVal, page, count);
    });

    $("#myTab").click(function (e) {
        var ev = e || window.event;
        var tar = ev.target;
        var tarp = $(tar).parent();
        var tarpi = $.trim(tarp[0].innerText);
        var tarpp = $(tarp).parent()[0];
        var index = tarpp.rowIndex;
        var da = tarpp.innerText.split("	");
        var val = tar.getAttribute("data-value");
        var that = this;
        if (tarpi == "修改") {
            console.log("--修改", da[5]);
            var sex;
            if (da[5] == "男") {
                $("input[type='radio'][value=0]").attr("checked", false);
                $("input[type='radio'][value=1]").attr("checked", true);
            } else {
                $("input[type='radio'][value=1]").attr("checked", false);
                $("input[type='radio'][value=0]").attr("checked", true);
            }
            $("input[name='editId']").val(da[0]);
            $("input[name='editName']").val(da[1]);
            $("input[name='editPasswd']").val(da[2]);
            $("input[name='editAddr']").val(da[3]);
            $("input[name='editTel']").val(da[4]);
            // $("input[name='editSex']").val(da[5]);
            $("input[name='editBirthday']").val(da[6]);

            $('#editModal').modal('show');
        } else if (tarpi == "添加") {
            $('#addModal').modal('show');
        } else if (tarpi == "删除") {
            console.log("--删除");
            var id = da[0];
            if (confirm("确认删除该条id为：" + id + " 的数据")) {
                delUser(id);
                searchVal = $(".search").val() || ""
                getSearchUser(searchVal, page, count)
            } else
                return;
        } else if (tarpi == '+') {
            if ($(".t_add").length < 1) {
                // var tb = document.getElementById("table1");
                var newTr = this.insertRow(index + 1); //表示在第二行后添加一行
                newTr.className = 't_add';
                // var newTd = newTr.insertCell(); //表示在添加的行上添加第一格
                newTr.insertCell().innerHTML = "<input type='text' disabled class='plusInput' name='t_addId'>";
                newTr.insertCell().innerHTML = "<input type='text' class='plusInput' name='t_addName'>";
                newTr.insertCell().innerHTML = "<input type='text' class='plusInput' name='t_addPasswd'>";
                newTr.insertCell().innerHTML = "<input type='text' class='plusInput' name='t_addAddr'>";
                newTr.insertCell().innerHTML = "<input type='text' class='plusInput' name='t_addTel'>";
                newTr.insertCell().innerHTML = "<label>男<input type='radio' checked name='t_addGender' value='1'></label><label>女<input type='radio' name='t_addSex' value='0'></label>";
                // newTr.insertCell().innerHTML = "<input type='text' class='plusInput' name='t_addWork'>";
                newTr.insertCell().innerHTML = "<input type='date' class='plusInput' name='t_addBirthday'>";

                newTr.insertCell().innerHTML = "<b class='glyphicon glyphicon-ok save' data-value='1'></b>";
                newTr.insertCell().innerHTML = "<b class='glyphicon glyphicon-refresh reset' data-value='0'></b>";
                newTr.insertCell().innerHTML = "<b class='glyphicon glyphicon-remove remove' data-value='-1'></b>";
                initDate();
            } else {
                alert("已经存在一行添加,请先完成！");
                return;
            }
        } else if (val == '1') { //提交
            var username = $("input[name='t_addName']").val();
            var passwd = $("input[name='t_addPasswd']").val();
            var tel = $("input[name='t_addTel']").val();
            var birthday = $("input[name='t_addBirthday']").val();
            var gender = $("input[name='t_addGender']:checked").val();
            var addr = $("input[name='t_addAddr']:checked").val();
            var sex;
            if (gender == 1) {
                sex = "男";
            } else {
                sex = "女";
            }

            var data = {
                "username": username,
                "passwd": passwd,
                "addr": addr,
                "gender": sex,
                "tel": tel,
                "birthday": birthday
            }

            var url = "http://127.0.0.1:8888/linkMan/linkman/addUser";
            operationUser(data, url);
            searchVal = $(".search").val() || ""
            getSearchUser(searchVal, page, count)
        } else if (val == '0') {
            console.log("000000");
            $("input[name='t_addId']").val("");
            $("input[name='t_addName']").val("");
            $("input[name='t_addPasswd']").val("");
            $("input[name='t_addAddr']").val("");
            $("input[name='t_addTel']").val("");
            $("input[name='t_addBirthday']").val("");
            // $("input[name='t_addAge']").val("");
            $("input[name='t_addGender'][value=1]").attr("checked", true);
            $("input[name='t_addGender'][value=0]").attr("checked", false);
        } else if (val == '-1') {
            this.deleteRow(index);
        } else {
            return;
        }
    });

    $("#addSubmit").click(function (event) {
        /* Act on the event */
        var username = $("input[name='addName']").val();
        var passwd = $("input[name='addPasswd']").val();
        var tel = $("input[name='addTel']").val();
        var addr = $("input[name='addAddr']").val();
        var birthday = $("input[name='addBirthday']").val();
        var gender = $("input[name='addSex']:checked").val();
        var sex;
        if (gender == 1) {
            sex = "男";
        } else {
            sex = "女";
        }
        var url = "http://127.0.0.1:8888/linkMan/linkman/addUser";
        var data = {
            "username": username,
            "passwd": passwd,
            "addr": addr,
            "gender": sex,
            "tel": tel,
            "birthday": birthday
        }
        operationUser(data, url); //连接后端，修改数据库
        searchVal = $(".search").val() || ""
        getSearchUser(searchVal, page, count);
        $("#addForm")[0].reset();
        initDate();
        $('#addModal').modal('hide');
    });

    $(".editBtn").click(function (event) {
        /* Act on the event */
        var username = $("input[name='editName']").val();
        var userId = $("input[name='editId']").val();
        var passwd = $("input[name='editPasswd']").val();
        var addr = $("input[name='editAddr']").val();
        var tel = $("input[name='editTel']").val();
        var birthday = $("input[name='editBirthday']").val();
        var gender = $("input[name='editSex']:checked").val();
        var url = "http://127.0.0.1:8888/linkMan/linkman/updateUser";

        var sex;
        if (gender == "1") {
            sex = "男";
        } else {
            sex = "女";
        }
        console.log("sex: ", sex)

        console.log(username, userId, passwd, addr, tel, birthday, sex);

        var data = {
            "id": userId,
            "username": username,
            "passwd": passwd,
            "addr": addr,
            "gender": sex,
            "tel": tel,
            "birthday": birthday
        }
        operationUser(data, url);
        $('#editModal').modal('hide');
        searchVal = $(".search").val() || ""
        getSearchUser(searchVal, page, count)
    });

    $(".first").click(function (event) {
        /* Act on the event */
        page = 1;
        // getPageData(page);
        // getAllPage();
        searchVal = $(".search").val() || ""
        getSearchUser(searchVal, page, count)
        $(".nowPage").val(page);
    });

    $(".pre").click(function (event) {
        /* Act on the event */
        if (page <= 1) {
            alert("已经是第一页了！");
            return;
        } else {
            page--;
            // getPageData(page);
            searchVal = $(".search").val() || ""
            getSearchUser(searchVal, page, count);
        }
        $(".nowPage").val(page);
    });

    $(".next").click(function (event) {
        /* Act on the event */
        if (page >= allPage) {
            alert("已经是最后一页了！");
            return;
        } else {
            page++;
            // getPageData(page);
            searchVal = $(".search").val() || ""
            getSearchUser(searchVal, page, count)
        }
        $(".nowPage").val(page);
    });

    $(".last").click(function (event) {
        /* Act on the event */
        page = allPage;
        // getPageData(page);
        searchVal = $(".search").val() || ""
        getSearchUser(searchVal, page, count)
        $(".nowPage").val(page);
    });

    $(".toBtn").click(function (event) {
        /* Act on the event */
        var toPage = $(".toPage").val();
        if (toPage <= 0) {
            alert("页数不小于1！");
            return;
        } else if (toPage > allPage) {
            alert("页数不能大于最大页数！" + allCount);
            return;
        } else {
            page = toPage;
            // getPageData(page);
            searchVal = $(".search").val() || ""
            getSearchUser(searchVal, page, count)
        }
    });
}